﻿using System;
using System.Configuration;
using zTalk.Network;

namespace zTalk
{
    class App
    {
        private Server server;

        public void Run()
        {
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);

            server = new Server();
            server.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);

            PacketReader.Handler = new PacketHandlerServer();
            UserManager.DB = new zTalkDataContext(
                ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString
            );
            Server.UserQuit += new ServerEventHandler(Server_UserQuit);

            try
            {
                UserManager.LogoutAll();
            }
            catch
            {
                Console.WriteLine("Cannot connect to database");
                return;
            }

            try
            {
                server.Start();
            }
            catch
            {
                Console.WriteLine("Cannot start server listener");
                return;
            }
        }

        void Server_UserQuit(object sender, ServerEventArgs ea)
        {
            SocketUser client = (SocketUser)ea.Result;
            try
            {
                UserManager.Logout(client.Username);

                UserProto[] friends = UserManager.GetNotifyFriends(client.UserID);

                foreach (var friend in friends)
                {
                    if (SocketUser.Users.ContainsKey(friend.Username))
                    {
                        Packet p = Packet.Create(Opcodes.USER_LOGOUT,
                            Json.Encode<string[]>(new string[] { client.Username }));
                        SocketUser.Users[friend.Username].SendPacket(p);
                    }
                }
            }
            catch { }
        }

        void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
            UserManager.LogoutAll();
            server.Shutdown();
            
            Console.WriteLine("Bye");
        }
    }
}
